var gulp = require('gulp')
var $ = require('gulp-load-plugins')()
var fs = require('fs')
var path = require('path')
var del = require('del')
// var colors = require('colors')
var child_process = require('child_process')

var theme = {}
var themeList = require('./src/element-ui/config.js').filter(item => !item.hasBuild)
var styleFileDir = './src/assets/scss'
var styleFileDirTemp = `${styleFileDir}-temp`
var themeFileDir = './public/element-theme'
var et = require('element-theme')
var etOptions = require('./package.json')['element-theme']
var themeFileName = etOptions.config.replace(/.*\/(.+\.scss)/, '$1')

gulp.task('themes', () => {
  if (themeList.length <= 0) { return del(styleFileDirTemp) }

  // del(styleFileDirTemp)

  // child_process.spawnSync('cp', ['-r', styleFileDir, styleFileDirTemp])

  // child_process.spawnSync('cp', ['-r', etOptions.config, styleFileDirTemp])
  etOptions.config = `${styleFileDirTemp}/${themeFileName}`

  fnCreate(themeList)

  function fnCreate (themeList) {
    if (themeList.length >= 1) {
      theme = themeList[0]

      var data = fs.readFileSync(etOptions.config, 'utf8')
      var result = data.replace(/\$--color-primary:(.*) !default;/, `$--color-primary:${theme.color} !default;`)
      fs.writeFileSync(path.resolve(etOptions.config), result)

      var data = fs.readFileSync(`${styleFileDirTemp}/aui.scss`, 'utf8')
      var result = data.replace(new RegExp(`(@import \")(.*\/)(${themeFileName}\";)`), '$1./$3')
      fs.writeFileSync(path.resolve(`${styleFileDirTemp}/aui.scss`), result)

      etOptions.out = `${themeFileDir}/${theme.name}`
      et.run(etOptions, () => {
        gulp.start(['styles'], () => {
          themeList.splice(0, 1)
          fnCreate(themeList)
        })
      })
    } else {
      del(styleFileDirTemp)

      var files = [
        `${themeFileDir}/**/*.css`,
        `!${themeFileDir}/**/index.css`,
        `!${themeFileDir}/**/aui.css`,
        `!${themeFileDir}/**/fonts`
      ]
      del(files)
    }
  }
})

gulp.task('styles', () => {
  return gulp.src([`${styleFileDirTemp}/aui.scss`])
    .pipe($.sass().on('error', $.sass.logError))
    .pipe($.autoprefixer({
      browsers: etOptions.browsers,
      cascade: false
    }))
    .pipe($.cleanCss())
    .pipe($.rename('aui.css'))
    .pipe(gulp.dest(`${themeFileDir}/${theme.name}`))
})
